package roof_extractor;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.NodeList;

public class TrovaCasaNetAnnuncio implements Annuncio{
	
	private Map<String,String> keyValues;
	private String filePath;
	
	private String getContent(NodeList nodes){
		String content = "";
		try {
			switch (nodes.getLength()) {
			case 0: content = null; break;
			case 1: content = (String) nodes.item(0).getChildNodes().item(0).getNodeValue(); break;	
			default:
				for(int i=0;i<nodes.getLength();i++){ 
					content = content.concat(nodes.item(i).getNodeValue().toString() + " ");	
				}
				break;
			}
		} catch (Exception e) {
			content = null;
		}
		return content;
	}
	
	public TrovaCasaNetAnnuncio(File file) throws IOException{
		
		this.keyValues = new HashMap<String, String>();
		this.filePath = file.getAbsolutePath();
		
		try {
			
			this.keyValues.put("tipologia",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Tipologia:']",file)));		
			this.keyValues.put("contratto",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Contratto:']",file)));
			this.keyValues.put("comune",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Comune:']//text()",file)));
			this.keyValues.put("prezzo",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Prezzo:']/span",file)).replaceAll("[^0-9]", ""));
			this.keyValues.put("locali",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Locali:']",file)).replaceAll("[^0-9]", ""));
			this.keyValues.put("superficie",this.getContent(Utils.getXPathFromFile("//td[../th/text()='Superficie:']",file)).replaceAll("[^0-9]", ""));
			this.keyValues.put("descrizione",this.getContent(Utils.getXPathFromFile("//p[@id='descrizione']",file)).toLowerCase());
			// This is a BAD XPath, but "//a[starts-with(@href,\"/agenzia.asp\")]" and "//a[@href~'/agenzia.asp']" don't work:
			this.keyValues.put("agenzia", this.getContent(Utils.getXPathFromFile("//p[a][b]//text()",file)));
			
			Pattern pattern = Pattern.compile("new GLatLng\\(\"(\\d+).(\\d+)\", \"(\\d+).(\\d+)\"\\)");
			Matcher matcher = pattern.matcher(Utils.fromFile(file.getAbsolutePath()));
			if(matcher.find()){
				this.keyValues.put("latitudine",matcher.group(1)+"."+matcher.group(2));
				this.keyValues.put("longitudine",matcher.group(3)+"."+matcher.group(4));
			}
			
						
		} catch (FileNotFoundException e) {
			System.out.println("File Not Found !!! [ " + file.getAbsolutePath() + " ]");
		} catch (XPathExpressionException e) {
			e.printStackTrace();
		}
		
		/*
		 * 	Some little editing with regex
		 */
		
		// Remove anything but the first numbers group from the area field
		Pattern pattern = Pattern.compile("[0-9]+");
		Matcher matcher = pattern.matcher(this.keyValues.get("superficie"));
		try{
			if(matcher.find()){ this.keyValues.put("superficie", matcher.group()); }
		} catch (Exception e) { }
		
		// Remove the scaling parameter from photo url, if exists
		if(this.keyValues.get("foto")!=null){
			this.keyValues.put("foto", this.keyValues.get("foto").replaceAll("&w=[0-9]+$", ""));
		}
		
		// Manage agency field
		try {
			String a = this.keyValues.get("agenzia").replace(':', ' ');
			if (!a.startsWith("Pubblicato da")) {
				this.keyValues.put("agenzia", "ignota");
			} else {
				a = a.replaceFirst("Pubblicato da(ll'agenzia)?", "");
				this.keyValues.put("agenzia", a);
			}
		} catch (Exception e) { }
		
		// Remove groups of scores from any field
		pattern = Pattern.compile("--+");
		for (String key : this.keyValues.keySet()){
			try{
				matcher = pattern.matcher(this.keyValues.get(key));
				while(matcher.find()){ this.keyValues.put(key, matcher.replaceAll("-")); }
			} catch (Exception e) { }
		}
		
		// Remove groups of white spaces from any field
		pattern = Pattern.compile("\\s\\s+");
		for (String key : this.keyValues.keySet()){
			try{
				matcher = pattern.matcher(this.keyValues.get(key));
				while(matcher.find()){ this.keyValues.put(key, matcher.replaceAll(" ")); }
			} catch (Exception e) { }
		}
		
//		// OLD, not needed anymore 
//		// Remove anything but the price from price field
//		pattern = Pattern.compile("[0-9]+.?[0-9]*.?[0-9]*,?[0-9]*");
//		try{
//			matcher = pattern.matcher(this.keyValues.get("prezzo"));
//			if(matcher.find()){ this.keyValues.put("prezzo", matcher.group()); }
//		} catch (Exception e) { }
//		
//		for (String key : this.keyValues.keySet()){
//			try{
//				this.keyValues.put(key, this.keyValues.get(key).trim());
//			} catch (Exception e) { }
//		}
		
	}
	
	public String getPrezzo() {
		return this.keyValues.get("prezzo");
	}
	public String getLocali() {
		return this.keyValues.get("locali");
	}
	public String getSuperficie() {
		return this.keyValues.get("superficie");
	}
	public String getIndirizzo() {
		return this.keyValues.get("comune");
	}
	public String getTipologia() {
		return this.keyValues.get("tipologia");
	}
	public String getContratto() {
		return this.keyValues.get("contratto");
	}
	public String getDescrizione() {
		return this.keyValues.get("descrizione");
	}
	public String getContatti() {
		return this.keyValues.get("agenzia");
	}
	public String getFilePath(){
		return this.filePath;
	}
	public String getLatitudine(){
		return this.keyValues.get("latitudine");
	}
	public String getLongitudine(){
		return this.keyValues.get("longitudine");
	}
	
	public void printData(){
		
		System.out.println("-----------------------------------");
		System.out.println(">>> Annuncio "+ this.getFilePath() +" <<<");
		System.out.println("Contratto: "   + this.getContratto());
		System.out.println("Tipologia: "   + this.getTipologia());
		System.out.println("Indirizzo: "   + this.getIndirizzo());
		System.out.println("Coordinate: "  + this.getLatitudine()+" - "+this.getLongitudine());
		System.out.println("Locali: "      + this.getLocali());
		System.out.println("Superficie: "  + this.getSuperficie());
		System.out.println("Prezzo: "      + this.getPrezzo());
		System.out.println("Descrizione: " + this.getDescrizione());
		System.out.println("Contatti: "    + this.getContatti());
		System.out.println("-----------------------------------");
	}

	public void save(String db_abs_filepath) throws ClassNotFoundException, SQLException {
		Utils.saveAnnuncio(db_abs_filepath,this);
		
	}

}
